package zct.proj.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import zct.proj.pojo.EquipDC;
import zct.proj.pojo.EquipXHJ;
import zct.proj.pojo.EquipmentInfo;
import zct.proj.pojo.LogicSwitcher;
import zct.proj.pojo.StationInfo;
import zct.proj.pojo.StationSummary;
import zct.proj.pojo.Switcher;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Environment;
import android.util.Log;

public class IniParser {
	
	private static String stationName;
	private final static String ZCT_PATH = "/zct";
//	private final static String ZCT_PATH = "/external_sd/zct";
	
	public static String getStationSoundPath() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File sddir = Environment.getExternalStorageDirectory();
			try {
				return (sddir.getCanonicalPath() + ZCT_PATH + "/stations/" + stationName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static String getSoundRootPath() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File sddir = Environment.getExternalStorageDirectory();
			try {
				return (sddir.getCanonicalPath() + ZCT_PATH + "/sound");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static HashMap<Integer, String> getJKXXList() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File sddir = Environment.getExternalStorageDirectory();
			try {
				FileInputStream fis = new FileInputStream(sddir.getCanonicalPath() + ZCT_PATH + "/stations/" + stationName + "/jkxx.ini");
				BufferedReader br = new BufferedReader(new InputStreamReader(fis, "GB2312"));
				HashMap<Integer, String> result = new HashMap<Integer, String>();
				String line = null;
				boolean dataStart = false;
				while ((line = br.readLine()) != null) {
					if (dataStart) {
						String[] tmp = line.split("=");
						String eName = tmp[1].replace(",", "");
						result.put(Integer.valueOf(tmp[0]), eName);
					} else {
						if (line.equals(Const.SECTION_XXB)) {
							dataStart = true;
						}
					}
				}
				return result;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Log.v("tag", "not ready");
		}
		return null;
	}
	
	/**
	 * 获取监控信息
	 * @param file
	 */
	public static HashMap<Integer, String> getJKXXList(Context ctx) {
//		AssetManager mgr = ctx.getResources().getAssets();
//		try {
//			InputStream ins = mgr.open("maps/jkxx.ini", AssetManager.ACCESS_STREAMING);
//			BufferedReader br = new BufferedReader(new InputStreamReader(ins, "GB2312"));
//			HashMap<Integer, String> result = new HashMap<Integer, String>();
//			String line = null;
//			boolean dataStart = false;
//			while ((line = br.readLine()) != null) {
//				if (dataStart) {
//					String[] tmp = line.split("=");
//					String eName = tmp[1].replace(",", "");
//					result.put(Integer.valueOf(tmp[0]), eName);
//				} else {
//					if (line.equals(Const.SECTION_XXB)) {
//						dataStart = true;
//					}
//				}
//			}
//			return result;
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
		return null;
	}
	
	/**
	 * 获取站场信息
	 * @param file 站场图配置文件
	 * @return
	 */
	public static StationInfo getStationInfo(String sName) {
		
		stationName = sName;
		
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File sddir = Environment.getExternalStorageDirectory();
			try {
				FileInputStream fis = new FileInputStream(sddir.getCanonicalPath() + ZCT_PATH + "/stations/" + sName + "/map.ini");
				BufferedReader br = new BufferedReader(new InputStreamReader(fis, "GB2312"));
				
				return parseStationInfo(br);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Log.v("tag", "not ready");
		}
		return null;
	}
	
	public static StationInfo getStationInfo(Context ctx) {
//		AssetManager mgr = ctx.getResources().getAssets();
//		try {
//			InputStream ins = mgr.open("maps/LYF.ini", AssetManager.ACCESS_STREAMING);
//			BufferedReader br = new BufferedReader(new InputStreamReader(ins, "GB2312"));
//			return parseStationInfo(br);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		
		return null;
	}
	
	/**
	 * 解析ini数据
	 * @param br
	 * @return
	 */
	private static StationInfo parseStationInfo(BufferedReader br) {

		StationInfo si = new StationInfo();
		String line = null;
		StationSummary summary = new StationSummary();
//		ArrayList<EquipmentInfo> sdiList = new ArrayList<EquipmentInfo>();
//		HashMap<String, Integer> switcherMap = new HashMap<String, Integer>();
//		ArrayList<Switcher> swList = new ArrayList<Switcher>();
		int flag = 0;
		int cnt = 0;
		try {
			while ((line = br.readLine()) != null) {
				if (line.startsWith(Const.SECTION_PREFIX)) {
					cnt = 0;
					if (line.equals(Const.SECTION_SUMMARY)) {
						// 概述
						flag = 1;
					} else if (line.equals(Const.SECTION_DETAIL)) {
						// 详述
						flag = 2;
//						cnt = 0;
					} else if (line.equals(Const.SECTION_XHJ)) {
						// 信号机
						flag = 3;
					} else if (line.equals(Const.SECTION_DHAN)) {
						// 灯或按钮
						flag = 4;
					} else if (line.equals(Const.SECTION_WCQD)) {
						// 无岔区段
						flag = 5;
					} else if (line.equals(Const.SECTION_DC)) {
						// 道岔
						flag = 6;
					} else if (line.equals(Const.SECTION_LJKG)) {
						// 逻辑开关量
						flag = 7;
					} else if (line.equals(Const.SECTION_DCBS)) {
						// 道岔表示
						flag = 8;
					} else {
						flag = 0;
					}
				} else if (!line.trim().equals("")) {
					cnt++;
					switch (flag) {
					case 1:
						// 概述
						parseSummary(line, summary);
						break;
					case 2:
						// 详述
						EquipmentInfo sdi = parseStationDetail(line);
						if (sdi != null) {
							si.ctlList.add(sdi);
							if (sdi.getName().equals(Const.EQUI_XHJ)) {
								si.xhjIdxList.add(si.ctlList.size() - 1);
							} else if (sdi.getName().equals(Const.EQUI_DC)) {
								si.dcIdxList.add(si.ctlList.size() - 1);
							} else if (sdi.getName().equals(Const.EQUI_DHAN)) {
								if (sdi.getType() == Const.TYPE_BTN_DCBS) {
									si.dcbsIdxList.add(si.ctlList.size() - 1);
								} else {
									si.dhanIdxList.add(si.ctlList.size() - 1);
								}
							} else if (sdi.getName().equals(Const.EQUI_JYJ)) {
								si.jyjIdxList.add(si.ctlList.size() - 1);
							} else if (sdi.getName().equals(Const.EQUI_WCQD)) {
								si.wcqdIdxList.add(si.ctlList.size() - 1);
							}
						}
						break;
					case 3:
						// 信号机
						parseXHJ(line, si);
						break;
					case 4:
						// 灯或按钮
						parseDHAN(line, si);
						break;
					case 5:
						if (cnt <= summary.getWcqdCount()) {
							// 无岔区段
							parseWCQD(line, si);
						}
						break;
					case 6:
						// 道岔
						parseDC(line, si);
						break;
					case 7:
						// 逻辑开关量
						if (cnt <= summary.getSwiCount()) {
							parseLJKG(line, si);
						}
						break;
					case 8:
						// 道岔表示
						parseDCBS(line, si);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		si.setStationSummary(summary);
		// 设定逻辑开关量与开关量的关联关系
		Iterator<Entry<String, LogicSwitcher>> it = si.lsMap.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, LogicSwitcher> entry = it.next();
			LogicSwitcher ls = entry.getValue();
			for (String name : ls.swNames) {
				Switcher sw = si.switcherMap.get(name);
				if (sw == null) {
					sw = new Switcher();
					si.switcherMap.put(name, sw);
				}
				sw.addRelateSwitcher(entry.getKey());
			}
		}
		return si;
	}
	
	private static EquipmentInfo parseStationDetail(String line) {
		
		String key = getKey(line);
		int id = Integer.valueOf(key.substring(Const.DETAIL_KEY_ID.length()));
		
		
		String value = getStringValue(line);
		String[] values = value.split(",");
		
		Object sdi = null;
		if (values[1].equals(Const.EQUI_XHJ)) {
			sdi = new EquipXHJ();
		} else if (values[1].equals(Const.EQUI_DC)) {
			sdi = new EquipDC();
		} else {
			sdi = new EquipmentInfo();
		}
		((EquipmentInfo)sdi).setId(id);
		((EquipmentInfo)sdi).setDisp(values[0]);
		((EquipmentInfo)sdi).setName(values[1]);
		((EquipmentInfo)sdi).setType(Integer.valueOf(values[2]));
//		sdi.setColor(transColor(Integer.valueOf(values[3])));
		// 默认颜色设置为灰色，不从ini文件中读取
		((EquipmentInfo)sdi).setColor(Color.GRAY);
		((EquipmentInfo)sdi).setDir(Integer.valueOf(values[4]));
		((EquipmentInfo)sdi).setX(Integer.valueOf(values[5]));
		((EquipmentInfo)sdi).setY(Integer.valueOf(values[6]));
		((EquipmentInfo)sdi).setWidth(Integer.valueOf(values[7]));
		((EquipmentInfo)sdi).setHeight(Integer.valueOf(values[8]));
		((EquipmentInfo)sdi).setFontsize(Integer.valueOf(values[9]));
		((EquipmentInfo)sdi).setTextColor(transColor(Integer.valueOf(values[10])));
		((EquipmentInfo)sdi).setFont(values[11]);
		((EquipmentInfo)sdi).setNameVisible(Integer.valueOf(values[12]));
		
		if (values[1].equals(Const.EQUI_XHJ)) {
			if (((EquipmentInfo)sdi).getType()  == Const.TYPE_XHJ_CFSDAZ
					|| ((EquipmentInfo)sdi).getType() == Const.TYPE_XHJ_CFSDGZ
					|| ((EquipmentInfo)sdi).getType() == Const.TYPE_XHJ_JZ
					|| ((EquipmentInfo)sdi).getType() == Const.TYPE_XHJ_QJ) {
				((EquipXHJ) sdi).lampCount = 2;
			} else {
				((EquipXHJ) sdi).lampCount = 1;
			}
			return (EquipXHJ)sdi;
		}
		
		return (EquipmentInfo)sdi;
	}
	
	private static void parseXHJ(String line, StationInfo si) {
		String[] tmp = line.split("=");
		//1=0,S,S-H;0;14,S-L;0;15,S-U;0;12,S-YB;0;13,;0;65535,;0;65535,;0;65535,;0;65535,;0;65535,;0;65535
		String[] data = tmp[1].split(",");
		int idx = Integer.valueOf(data[0]);
		int switcherIdx = si.xhjIdxList.get(idx);
		EquipXHJ ei = (EquipXHJ) si.getCtlList().get(switcherIdx);
		for (int i = 2; i < data.length; i++) {
			String[] items = data[i].split(";");
			if (items[0] != null && !"".equals(items[0])) {
				Switcher sw = si.switcherMap.get(items[0]);
				if (sw == null) {
					sw = new Switcher(0, switcherIdx);
					si.switcherMap.put(items[0], sw);
				} else {
					sw.addCtlIndex(switcherIdx);
				}
				
				// 将开关量映射至控件
				ei.addSwMapItem(items[0], i - 2);
			}
		}
	}
	
	private static void parseDHAN(String line, StationInfo si) {
		// 1=0,;0;65535,;0;65535,;0;65535,;0;65535,;0;65535,XMD-B;0;608
		String[] tmp = line.split("=");
		String[] data = tmp[1].split(",");
		int idx = Integer.valueOf(data[0]);
		int switcherIdx = si.dhanIdxList.get(idx);
		EquipmentInfo ei = si.getCtlList().get(switcherIdx);
		for (int i = 1; i < data.length; i++) {
			String[] items = data[i].split(";");
			if (items[0] != null && !"".equals(items[0])) {
				Switcher sw = si.switcherMap.get(items[0]);
				if (sw == null) {
					sw = new Switcher(0, switcherIdx);
					si.switcherMap.put(items[0], sw);
				} else {
					sw.addCtlIndex(switcherIdx);
				}
				
				// 将开关量映射至控件
				ei.addSwMapItem(items[0], i - 1);
			}
		}
	}
	
	private static void parseWCQD(String line, StationInfo si) {
		// 101=100,4G-3H;0;383,4G-2B;0;382
		String[] tmp = line.split("=");
		String[] data = tmp[1].split(",");
		int idx = Integer.valueOf(data[0]);
		int switcherIdx = si.wcqdIdxList.get(idx);
		EquipmentInfo ei = si.getCtlList().get(switcherIdx);
		for (int i = 1; i < data.length; i++) {
			String[] items = data[i].split(";");
			if (items[0] != null && !"".equals(items[0])) {
//				Switcher sw = new Switcher(0, switcherIdx);
//				si.switcherMap.put(items[0], sw);
				Switcher sw = si.switcherMap.get(items[0]);
				if (sw == null) {
					sw = new Switcher(0, switcherIdx);
					si.switcherMap.put(items[0], sw);
				} else {
					sw.addCtlIndex(switcherIdx);
				}
				// 将开关量映射至控件
				ei.addSwMapItem(items[0], i - 1);
			}
		}
	}
	
	private static void parseDC(String line, StationInfo si) {
		// 4=3,43,43-L;0;1608,43-U;0;1609,41FH;1;12,41FB;1;13,aaa1;0;65535,aaa2;0;65535,aaa3;0;65535,aaa4;0;65535
		String[] tmp = line.split("=");
		String[] data = tmp[1].split(",");
		int idx = Integer.valueOf(data[0]);
		int switcherIdx = si.dcIdxList.get(idx);
		EquipDC ei = (EquipDC) si.getCtlList().get(switcherIdx);
		
		for (int i = 2; i < data.length; i++) {
			String[] items = data[i].split(";");
			if (items[0] != null && !"".equals(items[0])) {
				Switcher sw = si.switcherMap.get(items[0]);
				if (sw == null) {
					sw = new Switcher(0, switcherIdx);
					si.switcherMap.put(items[0], sw);
				} else {
					sw.addCtlIndex(switcherIdx);
				}
				
				
				// 将开关量映射至控件
				if (i < 4) {
					ei.addSwPosListItem(items[0]);
				} else {
					ei.addSwMapItem(items[0], i - 2);
				}
			}
		}
	}
	
	private static void parseLJKG(String line, StationInfo si) {
		// 1=22DH,1,2,22-QH;0;0;293,22/26-L;0;0;1626,;0;0;65535
		String[] tmp = line.split("=");
		String[] data = tmp[1].split(",");
		LogicSwitcher ls = new LogicSwitcher();
		int swCount = Integer.valueOf(data[2]);
		ls.swCount = swCount;
		ls.method = Integer.valueOf(data[1]);
		ls.swNames = new String[swCount];
		ls.useReserve = new boolean[swCount];
		for (int i = 0; i < swCount; i++) {
			String[] items = data[i + 3].split(";");
			ls.swNames[i] = items[0];
			ls.useReserve[i] = (items[1].equals("1"));
		}
		si.lsMap.put(data[0], ls);
//		Log.v("parseLJKG", data[0]);
	}
	
	private static void parseDCBS(String line, StationInfo si) {
		// 1=0,2/4-L;0;1616,2/4-U;0;1617
		String[] tmp = line.split("=");
		String[] data = tmp[1].split(",");
		int idx = Integer.valueOf(data[0]);
		int switcherIdx = si.dcbsIdxList.get(idx);
		EquipmentInfo ei = si.getCtlList().get(switcherIdx);
		for (int i = 1; i < data.length; i++) {
			String[] items = data[i].split(";");
			if (items[0] != null && !"".equals(items[0])) {
//				Switcher sw = new Switcher(0, switcherIdx);
//				si.switcherMap.put(items[0], sw);
				Switcher sw = si.switcherMap.get(items[0]);
				if (sw == null) {
					sw = new Switcher(0, switcherIdx);
					si.switcherMap.put(items[0], sw);
				} else {
					sw.addCtlIndex(switcherIdx);
				}
				// 将开关量映射至控件
				ei.addSwMapItem(items[0], i - 1);
			}
		}
	}
	
	private static void parseSummary(String line, StationSummary summary) {
		
		if (line.startsWith(Const.SUMMARY_KEY_STATIONNAME)) {
			// 站名
			summary.setStationName(getStringValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_SCREENWIDTH)) {
			// 屏幕宽度
			summary.setScreenWidth(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_SCREENHEIGHT)) {
			// 屏幕高度
			summary.setScreenHeight(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_LINEWEIGHT)) {
			// 线宽
			summary.setLineWeight(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_XSPACING)) {
			// X网格大小
			summary.setXSpacing(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_YSPACING)) {
			// Y网格大小
			summary.setYSpacing(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_CTLCOUNT)) {
			// 控件总数
			summary.setCtlCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_DCCOUNT)) {
			// 道岔数目
			summary.setDcCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_XHJCOUNT)) {
			// 信号机数目
			summary.setXhjCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_WCQDCOUNT)) {
			// 无岔区段数目
			summary.setWcqdCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_BTNCOUNT)) {
			// 灯或按钮数目
			summary.setBtnCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_DCDISPCOUNT)) {
			// 道岔表示数目
			summary.setDcDispCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_JYJCOUNT)) {
			// 绝缘节数目
			summary.setJyjCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_TXTCOUNT)) {
			// 文本数目
			summary.setTxtCount(getIntValue(line));
		} else if (line.startsWith(Const.SUMMARY_KEY_SWICOUNT)) {
			// 逻辑开关量数目
			summary.setSwiCount(getIntValue(line));
		}
	}
	
	private static int getIntValue(String line) {
		String s = getStringValue(line);
		return Integer.valueOf(s);
	}
	
	private static String getStringValue(String line) {
		String[] tmp = line.split("=");
		if (tmp.length == 2) {
			return tmp[1];
		} else {
			return null;
		}
	}
	
	private static String getKey(String line) {
		return line.substring(0, line.indexOf("="));
	}
	
	public static int transColor(int color) {
		int b = color >> 16;
		int g = (color >> 8) & 255;
		int r = color & 255;
//		Log.v("color", color + ":" + r + "," + g + "," + b);
		return Color.rgb(r, g, b);
	}
}
